const fs = require('node:fs/promises')

// File Size Copied: 1GB
// Memory Usage: 1GB
// Execution Time: 900ms
// ;(async () => {
//   console.time('copy')
//   const destFile = await fs.open('text-copy.txt', 'w')
//   const result = await fs.readFile('text-big.txt', 'r')

//   await destFile.writeFile(result)
//   console.timeEnd('copy')
// })()

// File Size Copied: 1GB
// Memory Usage: 30MB
// Execution Time: 4.14s
// ;(async () => {
//   console.time('copy')
//   const destFile = await fs.open('file-copy.txt', 'w')
//   const srcFile = await fs.open('file-big.txt', 'r')

//   let bytesRead = -1

//   while (bytesRead !== 0) {
//     const readResult = await srcFile.read()
//     bytesRead = readResult.bytesRead

//     // 如果读取的字节数不等于16384，则说明读取的数据不完整，需要处理
//     if (bytesRead !== 16384) {
//       // 找到未填充的字节位置
//       const indexOfNotFilled = readResult.buffer.indexOf(0)
//       // 创建一个新的Buffer，大小为未填充的字节数
//       const newBuffer = Buffer.alloc(indexOfNotFilled)
//       // 将读取的数据复制到新的Buffer中
//       readResult.buffer.copy(newBuffer, 0, 0, indexOfNotFilled)
//       destFile.write(newBuffer)
//     } else {
//       await destFile.write(readResult.buffer)
//     }
//   }
//   console.timeEnd('copy')
// })()

// File Size Copied: 1GB
// Memory Usage: 30MB
// Execution Time: 1.3s
;(async () => {
  console.time('copy')
  const destFile = await fs.open('file-copy.txt', 'w')
  const srcFile = await fs.open('file-big.txt', 'r')

  const writeStream = destFile.createWriteStream()
  const readStream = srcFile.createReadStream()

  readStream.pipe(writeStream)

  readStream.on('end', () => {
    console.timeEnd('copy')
  })
})()
